﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Web;
using System.Web.UI;
using BikeBouncer.BusinessLayer;
using BikeBouncer.BusinessLayer.Entities;
using Devv.Core.Utils;
using MessagingToolkit.QRCode.Codec;

namespace BikeBouncer.Site
{
	public partial class BarcodeImg_aspx : Page
	{
		#region Page methods

		protected void Page_Load(Object sender, EventArgs e)
		{
			Int32 id = Item.KeyToId(Request.QueryString["k"]);
			String codeType = Request.QueryString["t"];
            Item item = new Item(id);

			if (item.Id < 1 || codeType.Length < 2)
			{
				ShowError();
			}
			else
			{
				Response.Clear();
				Response.ContentType = "image/png";
				Response.Cache.SetExpires(DateTime.Now.AddDays(1));
				Response.Cache.SetCacheability(HttpCacheability.Public);
				Response.Cache.SetVaryByCustom("*");

				codeType = codeType.ToLower();

				if (codeType == "qrcode")
				{
					GenerateQRCode(item);
				}
				else if (codeType == "datamatrix")
				{
					GenerateDataMatrix(item);
				}
				else
				{
					ShowError();
				}
			}
		}

		private void GenerateQRCode(Item item)
		{
            String path = Settings.ItemBarcodesPath + item.Id + ".qrcode.png";

			if (File.Exists(path))
			{
				Response.WriteFile(path);
				return;
			}
			
			QRCodeEncoder enc = new QRCodeEncoder();
			
			enc.QRCodeBackgroundColor = Color.White;
			enc.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.ALPHA_NUMERIC;
			enc.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.Q;
			enc.QRCodeForegroundColor = Color.Black;
			enc.QRCodeScale = 5;
			enc.QRCodeVersion = 3;

			Bitmap bmp = enc.Encode(item.KeyUrl);
            bmp.Save(path, ImageFormat.Png);

			Response.WriteFile(path);
		}

		private void GenerateDataMatrix(Item item)
		{
			String path = Settings.ItemBarcodesPath + item.Id + ".datamatrix.png";

			if (File.Exists(path))
			{
				Response.WriteFile(path);
				return;
			}

			WebClient client = new WebClient();
			client.Headers.Add(HttpRequestHeader.Referer, ConfigUtil.GetConfig("Barcode.DataMatrix.BaseUrl"));
			client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0)");
			client.DownloadFile(ConfigUtil.GetConfig("Barcode.DataMatrix.BaseUrl") + item.KeyUrl, path);

			Response.WriteFile(path);
		}

		#endregion

		#region Error

		private void ShowError()
		{
			Response.Clear();
			Response.ContentType = "image/gif";

			Response.WriteFile(Settings.BasePath + "Images\\InvalidBarcode.gif");
		}

		#endregion
	}
}
